<template>
  <div class="config-manager-container">
    <div class="card">
      <div class="card-header">
        <h2 class="card-title">配置管理</h2>
      </div>
      <div class="card-body">
        <!-- 配置操作选项卡 -->
        

        <!-- 选项卡内容 -->
        <div class="tab-content">
          <!-- 模型配置选项卡 -->
          <div 
            class="tab-pane fade show active" 
            id="model-config" 
            role="tabpanel" 
            aria-labelledby="model-config-tab"
          >
            <div v-if="modelConfigLoading" class="text-center py-4">
              <div class="spinner-border" role="status">
                <span class="visually-hidden">加载中...</span>
              </div>
              <p class="mt-2">正在加载模型配置...</p>
            </div>
            
            <div v-else-if="modelConfigError" class="alert alert-danger">
              {{ modelConfigError }}
            </div>
            
            <div v-else-if="modelConfig" class="model-config-form">
              <div class="mb-3">
                <label for="model-select" class="form-label">模型名称:</label>
                <input type="text" class="form-control" id="model-select" v-model="modelConfig.model" readonly>
              </div>
              
              <div class="mb-3">
                <label for="avatar-id" class="form-label">头像ID:</label>
                <input type="text" class="form-control" id="avatar-id" v-model="modelConfig.avatar_id">
              </div>
              
              <div class="mb-3">
                <label for="llm-type" class="form-label">LLM类型:</label>
                <select 
                  class="form-select" 
                  id="llm-type" 
                  v-model="modelConfig.llm_type"
                  @change="onLlmTypeChange"
                >
                  <option value="coze">Coze</option>
                  <option value="openai">OpenAI兼容API</option>
                </select>
              </div>
              
              <!-- OpenAI兼容API配置 -->
              <div v-if="modelConfig.llm_type === 'openai'" class="mb-4 p-3 bg-light rounded">
                <h4>OpenAI兼容API配置</h4>
                <div class="mb-3">
                  <label for="openai-api-key" class="form-label">API密钥:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="openai-api-key" 
                    v-model="openaiConfig.api_key"
                    placeholder="输入OpenAI API密钥"
                  >
                </div>
                <div class="mb-3">
                  <label for="openai-base-url" class="form-label">基础URL:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="openai-base-url" 
                    v-model="openaiConfig.base_url"
                    placeholder="输入API基础URL"
                  >
                </div>
                <div class="mb-3">
                  <label for="openai-model" class="form-label">模型名称:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="openai-model" 
                    v-model="openaiConfig.model"
                    placeholder="输入模型名称"
                  >
                </div>
                <div class="mb-3">
                  <label for="openai-system-prompt" class="form-label">系统提示词:</label>
                  <textarea 
                    class="form-control" 
                    id="openai-system-prompt" 
                    v-model="openaiConfig.system_prompt"
                    placeholder="输入系统提示词"
                    rows="2"
                  ></textarea>
                </div>
                <div class="mb-3 form-check">
                  <input 
                    type="checkbox" 
                    class="form-check-input" 
                    id="openai-stream" 
                    v-model="openaiConfig.stream"
                  >
                  <label class="form-check-label" for="openai-stream">使用流式输出</label>
                </div>
                <div class="mb-3 form-check">
                  <input 
                    type="checkbox" 
                    class="form-check-input" 
                    id="openai-include-usage" 
                    v-model="openaiConfig.stream_options.include_usage"
                    :disabled="!openaiConfig.stream"
                  >
                  <label class="form-check-label" for="openai-include-usage">显示token使用信息</label>
                </div>
              </div>
              
              <!-- Coze配置 -->
              <div v-if="modelConfig.llm_type === 'coze'" class="mb-4 p-3 bg-light rounded">
                <h4>Coze配置</h4>
                <div class="mb-3">
                  <label for="coze-api-token" class="form-label">API令牌:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="coze-api-token" 
                    v-model="cozeConfig.api_token"
                    placeholder="输入Coze API令牌"
                  >
                </div>
                <div class="mb-3">
                  <label for="coze-workflow-id" class="form-label">工作流ID:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="coze-workflow-id" 
                    v-model="cozeConfig.workflow_id"
                    placeholder="输入Coze工作流ID"
                  >
                </div>
                <div class="mb-3">
                  <label for="coze-base-url" class="form-label">基础URL:</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    id="coze-base-url" 
                    v-model="cozeConfig.base_url"
                    placeholder="输入Coze API基础URL"
                  >
                </div>
              </div>
              
              <button 
                class="btn btn-primary" 
                @click="updateModelConfig"
                :disabled="savingModelConfig"
              >
                <i v-if="savingModelConfig" class="bi bi-spinner bi-spin mr-2"></i>
                {{ savingModelConfig ? '保存中...' : '保存模型配置' }}
              </button>
            </div>
            
            <div v-if="modelConfigMessage" class="mt-3">
              <div :class="['alert', modelConfigSuccess ? 'alert-success' : 'alert-danger']">
                {{ modelConfigMessage }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ConfigService from '../services/ConfigService.js';

export default {
  name: 'ConfigManager',
  data() {
    return {
      // 模型配置相关
      modelConfig: null,
      llmConfigString: '',
      modelConfigLoading: false,
      modelConfigError: '',
      savingModelConfig: false,
      modelConfigMessage: '',
      modelConfigSuccess: false,
      
      // LLM配置对象
      openaiConfig: {
        api_key: '',
        base_url: '',
        model: '',
        system_prompt: '',
        stream: true,
        stream_options: {
          include_usage: true
        }
      },
      cozeConfig: {
        api_token: '',
        workflow_id: '',
        base_url: ''
      }
    };
  },
  mounted() {
    // 初始加载模型配置
    this.loadModelConfig().then(() => {
      // 配置加载完成后，确保显示正确的配置表单
      if (this.modelConfig && this.modelConfig.llm_type) {
        console.log('挂载完成，当前LLM类型:', this.modelConfig.llm_type);
        console.log('挂载完成，cozeConfig状态:', this.cozeConfig);
        // 强制触发一次onLlmTypeChange以确保所有配置正确设置
        this.onLlmTypeChange();
      }
    });
  },
  methods: {
    
    // LLM类型切换处理
    onLlmTypeChange() {
      // 确保modelConfig存在
      if (!this.modelConfig) {
        return;
      }
      
      console.log('LLM类型切换为:', this.modelConfig.llm_type);
    },
    
    // 加载模型配置
    async loadModelConfig() {
      this.modelConfigLoading = true;
      this.modelConfigError = '';
      try {
        console.log('开始加载模型配置...');
        this.modelConfig = await ConfigService.getModelConfig();
        console.log('获取到的模型配置:', JSON.stringify(this.modelConfig));
        
        // 确保modelConfig对象存在
        if (!this.modelConfig) {
          console.log('未获取到模型配置，创建默认配置');
          this.modelConfig = {
            model: '',
            avatar_id: '',
            llm_type: 'coze',
            llm_config: {}
          };
        }
        
        // 确保llm_type存在
        if (!this.modelConfig.llm_type) {
          console.log('模型配置中没有llm_type，默认设为coze');
          this.modelConfig.llm_type = 'coze';
        }
        
        // 确保llm_config存在
        if (!this.modelConfig.llm_config) {
          console.log('模型配置中没有llm_config，创建空对象');
          this.modelConfig.llm_config = {};
        }
        
        // 将获取到的配置值赋值给表单字段
        if (this.modelConfig.llm_config.openai) {
          this.openaiConfig = { ...this.modelConfig.llm_config.openai };
        }
        
        if (this.modelConfig.llm_config.coze) {
          this.cozeConfig = { ...this.modelConfig.llm_config.coze };
        }
        
        // 将llm_config对象转换为字符串
        this.llmConfigString = JSON.stringify(this.modelConfig.llm_config || {}, null, 2);

        
        console.log('加载完成后的cozeConfig状态:', JSON.stringify(this.cozeConfig));
        console.log('当前LLM类型:', this.modelConfig.llm_type);
        
        // 强制更新Vue实例的数据，确保响应性
        this.$forceUpdate();
        
      } catch (err) {
        console.error('加载模型配置时出错:', err);
        this.modelConfigError = `加载模型配置失败: ${err.message || '未知错误'}`;
        // 出错时也确保cozeConfig有默认值
        this.cozeConfig = { api_token: '', workflow_id: '', base_url: 'https://api.coze.cn' };
        console.log('错误处理后设置的cozeConfig:', JSON.stringify(this.cozeConfig));
      } finally {
        this.modelConfigLoading = false;
      }
    },
    
    // 更新模型配置
    async updateModelConfig() {
      if (!this.modelConfig) {
        this.modelConfigMessage = '请先加载模型配置';
        this.modelConfigSuccess = false;
        return;
      }
      
      // 根据选择的LLM类型构建配置对象
      let llmConfigObj = {};
      if (this.modelConfig.llm_type === 'openai') {
        llmConfigObj = { openai: { ...this.openaiConfig } };
      } else if (this.modelConfig.llm_type === 'coze') {
        llmConfigObj = { coze: { ...this.cozeConfig } };
      }
      
      const modelConfigToUpdate = {
        model: this.modelConfig.model,
        avatar_id: this.modelConfig.avatar_id,
        llm_type: this.modelConfig.llm_type,
        llm_config: llmConfigObj
      };
      
      this.savingModelConfig = true;
      this.modelConfigMessage = '';
      try {
        const result = await ConfigService.updateModelConfig(modelConfigToUpdate);
        if (result.success) {
          this.modelConfigMessage = '模型配置更新成功';
          this.modelConfigSuccess = true;
        } else {
          this.modelConfigMessage = `模型配置更新失败，失败项: ${result.failed.join(', ')}`;
          this.modelConfigSuccess = false;
        }
      } catch (err) {
        this.modelConfigMessage = `更新模型配置失败: ${err.message || '未知错误'}`;
        this.modelConfigSuccess = false;
      } finally {
        this.savingModelConfig = false;
      }
    }
  }
};
</script>

<style scoped>
.config-manager-container {
  width: 100%;
  padding: 0;
}

/* 调整卡片样式，使其适应侧边栏 */
.card {
  border: none;
  border-radius: 0;
  box-shadow: none;
}

.card-header {
  background-color: transparent;
  border-bottom: 1px solid #dee2e6;
  padding: 0.75rem 1rem;
}

.card-header h2.card-title {
  font-size: 1.25rem;
  margin: 0;
  text-align: center;
}

.card-body {
  padding: 0.75rem 0.5rem;
}

/* 选项卡样式调整 */
.mb-4 {
  margin-bottom: 1rem !important;
}

.nav-tabs {
  margin-bottom: 1rem;
}

.nav-link {
  padding: 0.5rem 0.75rem;
  font-size: 0.875rem;
}

.nav-link.active {
  background-color: #f8f9fa;
}

/* 表单样式调整 */
.model-config-form {
  width: 100%;
}

.mb-3 {
  margin-bottom: 0.75rem !important;
}

.form-label {
  font-size: 0.875rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.form-control,
.form-select {
  font-size: 0.875rem;
  padding: 0.25rem 0.5rem;
}

.form-control {
  height: calc(1.8em + 0.5rem + 2px);
}

textarea.form-control {
  min-height: calc(2.8em + 0.5rem + 2px);
}

/* OpenAI/Coze配置区块样式 */
.mb-4.p-3.bg-light.rounded {
  margin-bottom: 1rem !important;
  padding: 0.75rem !important;
}

.mb-4.p-3.bg-light.rounded h4 {
  font-size: 1rem;
  margin-bottom: 0.5rem;
  text-align: center;
}

/* 按钮样式调整 */
.btn.btn-primary {
  width: 100%;
  font-size: 0.875rem;
  padding: 0.5rem;
  margin-top: 0.5rem;
}

/* 提示信息样式 */
.alert {
  margin-top: 0.75rem;
  font-size: 0.875rem;
  padding: 0.5rem;
}

/* 加载状态样式 */
.text-center.py-4 {
  padding: 1rem 0;
}

.spinner-border {
  width: 1rem;
  height: 1rem;
}

/* 滚动条样式 */
.tab-content {
  max-height: calc(100vh - 150px);
  overflow-y: auto;
  padding-right: 0.5rem;
}

/* 自定义滚动条 */
.tab-content::-webkit-scrollbar {
  width: 4px;
}

.tab-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.tab-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.tab-content::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>